from device.device_base import DeviceBase
import cv2
from utils.img import load_image
import numpy as np

class Button:
    def __init__(self, name:str, img_path:str, device:DeviceBase):
        self.device = device
        self.x = 0
        self.y = 0
        self.width = 0
        self.height = 0
        self.name = name
        self.inited = False
        self.img_path = img_path

    def tap(self, ratio:float=0.2, wait:bool=False):
        if not self.inited:
            self.init()
        x = self.x + int(self.width/2 * ratio)
        y = self.y + int(self.height/2 * ratio)
        if wait:
            self.device.waiting_screen_changed(func=self.device.tap, x=x, y=y)
        else:
            self.device.tap(x, y)
    def init(self) -> bool:
        template = load_image(self.img_path)
        points = self.device.find_image(template)
        if len(points) == 0: return False
        self.width = template.shape[1]
        self.height = template.shape[0]
        self.x = points[0][0] + self.width//2
        self.y = points[0][1] + self.height//2
        self.inited = True
        return True